package medium;

/**
 * Created by daodao on 2017/11/30.
 * Problem 2
 * Description: You are given two non-empty linked lists representing two non-negative integers.
 * The digits are stored in reverse order and each of their nodes contain a single digit.
 * Add the two numbers and return it as a linked list.
 * You may assume the two numbers do not contain any leading zero, except the number 0 itself.
 *
 * Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
 *          Output: 7 -> 0 -> 8
 */
public class AddTwoNumbers {
    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode curL1 = l1;
        ListNode curL2 = l2;
        int sum = curL1.val + curL2.val;
        int carryBit = sum < 10 ? 0 : 1;
        ListNode head = new ListNode(sum % 10);
        ListNode point = head;
        while (curL1.next != null && curL2.next != null) {
            curL1 = curL1.next;
            curL2 = curL2.next;
            sum = curL1.val + curL2.val + carryBit;
            carryBit = sum < 10 ? 0 : 1;
            ListNode temp = new ListNode(sum % 10);
            point.next = temp;
            point = temp;
        }
        if (curL1.next != null) {
            while (curL1.next != null) {
                curL1 = curL1.next;
                sum = curL1.val + carryBit;
                carryBit = sum < 10 ? 0 : 1;
                ListNode temp = new ListNode(sum % 10);
                point.next = temp;
                point = point.next;
            }
        } else if (curL2.next != null) {
            while (curL2.next != null) {
                curL2 = curL2.next;
                sum = curL2.val + carryBit;
                carryBit = sum < 10 ? 0 : 1;
                ListNode temp = new ListNode(sum % 10);
                point.next = temp;
                point = point.next;
            }
        }
        if (carryBit > 0){
            point.next = new ListNode(carryBit);
        }
        return head;
    }
}
